import json
import re
import pdfplumber
import common

fields = ["Code", "Name"]
tag = "Icd10"
server = common.ServerRemoteRelease

def format_code():
    last_index = 0
    has_more = True
    page_index = 1
    while has_more:
        query_message = {
            "fields": fields,
            "pageIndex": page_index,
            "pageSize": 200,
            "lastIndex": last_index,
            "filters": [
                {"cmd":12,"args":["Code","\n"]},
            ]
        }
        query_message = json.dumps(query_message, ensure_ascii=False)
        arm = common.page(tag, query_message, server=server)
        arm = json.loads(arm)
        last_index = arm['data']['lastIndex']
        has_more = len(arm['data']['data']) >= 200
        actions = []
        for record in arm['data']['data']:
            rec_id = record['_id']
            code = record['Code'].replace('\n', '').replace('+', '†').replace(' ','')
            action = {
                'action': 23,
                'tag': 'Code',
                '_id': int(rec_id),
                'fv': code
            }
            actions.append(action)
        if len(actions) > 0:
            edit_message = {'actions': actions}
            edit_message = json.dumps(edit_message, ensure_ascii=False)
            print(edit_message)
            common.batch_modify(tag, edit_message, server=server)
        page_index += 1

def change_code():
    icd_10_code_pattern = re.compile(r'^[A-Z]\d{2}\.\d+x\d{5}$')
    # icd_10_code_pattern_new = re.compile(r'^[A-Z]\d{2}\.\d{3}')
    last_index = 0
    has_more = True
    page_index = 1
    while has_more:
        query_message = {
            "fields": fields,
            "pageIndex": page_index,
            "pageSize": 200,
            "lastIndex": last_index,
            "filters":[
                {"cmd":16,"args":["Code","00"]},
                # {"cmd":12,"args":["Code","*"]},
            ]
        }
        query_message = json.dumps(query_message, ensure_ascii=False)
        # print(query_message)
        arm = common.page(tag, query_message)
        arm = json.loads(arm)
        last_index = arm['data']['lastIndex']
        has_more = len(arm['data']['data']) >= 200
        actions = []
        for record in arm['data']['data']:
            rec_id = record['_id']
            code = record['Code']
            # print(code)
            if re.match(icd_10_code_pattern, code):
                code = code[:-2]
                # code = re.search(icd_10_code_pattern_new, code)
                # code = code.group()
        #         code += "00"
        #         print(code)
                action = {
                    'action': 23,
                    'tag': 'Code',
                    '_id': int(rec_id),
                    'fv': code
                }
                actions.append(action)
        if len(actions) > 0:
            edit_message = {'actions': actions}
            edit_message = json.dumps(edit_message, ensure_ascii=False)
            print(edit_message)
            common.batch_modify(tag, edit_message, server=server)
        page_index += 1


def format_name():
    last_index = 0
    has_more = True
    page_index = 1
    while has_more:
        query_message = {
            "fields": fields,
            "pageIndex": page_index,
            "pageSize": 200,
            "lastIndex": last_index,
            "filters": [
                {"cmd":12,"args":["Name","\n"]},
            ]
        }
        query_message = json.dumps(query_message, ensure_ascii=False)
        arm = common.page(tag, query_message, server=server)
        arm = json.loads(arm)
        last_index = arm['data']['lastIndex']
        has_more = len(arm['data']['data']) >= 200
        actions = []
        for record in arm['data']['data']:
            rec_id = record['_id']
            name = record['Name'].replace('\n', '').replace(' ','')
            action = {
                'action': 23,
                'tag': 'Name',
                '_id': int(rec_id),
                'fv': name
            }
            actions.append(action)
        if len(actions) > 0:
            edit_message = {'actions': actions}
            edit_message = json.dumps(edit_message, ensure_ascii=False)
            print(edit_message)
            common.batch_modify(tag, edit_message, server=server)
        page_index += 1

def append():
    with pdfplumber.open("/Users/zhujianfeng/ICD-10医保2.0版.pdf") as pdf:
        for page in pdf.pages:
            table = page.extract_table()
            skipped_rows_table = table[1:]
            records = []
            for row in skipped_rows_table:
                records.append({
                    fields[0]: row[9].strip().replace('+', '†').replace("\n",""),
                    fields[1]: row[10].strip().replace("\n","")
                })
            msg = json.dumps({
                "fields": fields,
                "records": records
            }, ensure_ascii=False)
            # print(msg)
            common.batch_add(tag, msg, server=server)

if __name__ == "__main__":
    append()
